<template>
	<div class="coursewareContent">
		<el-row :gutter="20" >

			<el-col :xs="18" :sm="18" :md="18" :lg="18" class="middleCol" >
				<div class="content" id = "middleCol">
					<div class="stageQuizTitle" v-if="state.info.paper_type === 2">
						{{state.info.title}}
					</div>
					<el-divider style="width: 120%; margin-left: -30px" />
					<template v-for="(item,index) in state.question" :key="index">
						<template v-if="item.quest.subQuestion[0].template === 'XuanZe'">
							<XuanZe :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-'+getRealIndex(index+1)" :seq="index+1"></XuanZe>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'PanDuan'">
							<PanDuan :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></PanDuan>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'TianKong'">
							<TianKong :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></TianKong>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'PaiXu'">
							<PaiXu :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></PaiXu>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'LianXian'">
							<LianXian :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></LianXian>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'ZuoDa'">
							<ZuoDa :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></ZuoDa>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'LangDu'">
							<LangDu :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></LangDu>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'XieZi'">
							<ShuXie :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></ShuXie>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'Card'">
							<Card :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></Card>
						</template>

						<template v-if="item.quest.subQuestion[0].template === 'DuiHua'">
							<DuiHua :question = "item" :questIndex="getRealIndex(index+1)" :id ="'quest-' + getRealIndex(index+1)" :seq="index+1"></DuiHua>
						</template>
						<el-divider style="width: 120%; margin-left: -30px; " />
					</template>
				</div>
			</el-col>
			<el-col :xs="5" :sm="5" :md="5" :lg="5">
				<div class="answerSheets">
					<div class="top">
						<div class="title">答题卡</div>
						<div class="questionNumberBox">
							<div @click="scollIntoIndexQuest(index+1)" :class="!isHaveAnswer(getFakeIndex(item)) ? 'questionNumber commonQuestionNum':'ActiveQuestionNum commonQuestionNum'" v-for="(item,index) in state.question.filter((item1) => {
								return item1.quest.asTitle!==true;
							})">
								{{ index + 1 }}
							</div>
						</div>
					</div>
					<div class="timer" v-if="!(state.info.paper_type === 0)">
						<div class="top">
							<van-count-down
								ref="countDown"
								:auto-start="true"
								:time="state.value"
								class="timer"
							/>
							<van-grid
								:column-num="1"
								clickable
							>
								<van-grid-item text="暂停作答" icon="pause-circle-o" @click="pause" />
							</van-grid>
						</div>
					</div>

					<div class="bottom">
						<el-button type="primary" :loading="state.exportLoading" @click="handleExport()" >导 出</el-button>
						<el-button type="primary" @click="submit">提 交</el-button>
					</div>
				</div>

			</el-col>
		</el-row>
		<el-dialog
			v-model="state.dialogVisible"
			title="Tips" width="500"
			draggable
			:show-close="false"
		>
			<div v-if="state.timingStatus === 2">
				<div>暂停中.........</div>
			</div>
			<div v-else>即将进入定时模式</div>
			<div>总时长：{{transformTime(state.info.time_length).min}}分钟</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button v-if="state.timingStatus === 2" type="primary" @click="startTimingPractice">开始作答</el-button>
					<el-button v-else type="primary" @click="onConfirm">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog
			v-model="state.centerDialogVisible"
			title="Notice"
			width="500"
			destroy-on-close
			center
			:show-close = "false"
		>
		    <span>
		      还有题目没做完，确定要提交吗？
		    </span>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="state.centerDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmit">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>


		<el-drawer
			v-model="state.drawer"
			title="I am the title"
			:with-header="false"
			@closed = "backSystem"
		>
			<div class="drawer">
				<span>真棒，恭喜你做完了所有试题!!</span>
				<el-image
					style="width: 200px; height: 200px"
					:src="String(successPath)"
					fit="contain"
				/>
				<el-button @click="backSystem">回到首页</el-button>
			</div>
		</el-drawer>
	</div>
</template>




<script setup lang="ts">
import {onMounted,ref,nextTick} from "vue";
import {useRoute} from "vue-router";
import {reactive} from "vue-demi";
import api from "@/api";
import XuanZe from "@/components/questionType/XuanZe/XuanZe.vue";
import {useDataStore} from "@/stores/useDataStore";
import {ElMessage} from "element-plus";
import router1 from '@/router';
import PanDuan from "@/components/questionType/PanDuan/PanDuan.vue";
import TianKong from "@/components/questionType/TianKong/TianKong.vue";
import PaiXu from "@/components/questionType/PaiXu/PaiXu.vue";
import LianXian from "@/components/questionType/LianXian/LianXian.vue";
import ZuoDa from "@/components/questionType/ZuoDa/ZuoDa.vue";
import LangDu from "@/components/questionType/LangDu/LangDu.vue";
import ShuXie from "@/components/questionType/ShuXie/ShuXie.vue";
import Card from "@/components/questionType/Card/Card.vue";
import DuiHua from "@/components/questionType/DuiHua/DuiHua.vue";

import { htmlToPDF } from '@/utils/html2pdf'


const router = useRoute();
const userAnswerStore = useDataStore();
const state = reactive({
	coursewareId: 0,
	classId: 0,
	shareId: 0,
	start_time: 0,
	question: [],
	questionLength: 0, //因为会有默认的卡片标题，所以要计算一下实际的题目数量
	value: 0,
	info: {},
	dialogVisible: false,
	timingStatus: -1,
	centerDialogVisible: false,
	drawer: false,
	layout: {
		left: 4,
		middle: 16,
		right: 4
	},
	exportLoading: false
})


const backSystem = () => {
	router1.push('/system')
}
const countDown = ref(null);

// import { createRequire } from 'module';
// const require = createRequire(import.meta.url);

const successPath = new URL('@/assets/success.jpg',import.meta.url)
const start = () => {
	countDown.value?.start();
};
const pause = () => {
	countDown.value?.pause();
	state.timingStatus =2;
	pauseTimingPractice()
	state.dialogVisible = true;
};
onMounted(async () => {
	state.coursewareId = router.query.coursewareId ? Number(router.query.coursewareId) : 0;
	state.classId = router.query.classId ? Number(router.query.classId) : 0;
	state.shareId = router.query.shareId ? Number(router.query.shareId) : 0;
	state.start_time = Date.now();
	const data = {
		group_id: state.coursewareId
	}
	const res = await api.GetCoursewareInfo(data)
	console.log(res)
	if (res && res.data.code === 200) {
		state.info = res.data.data.info;
		state.question = res.data.data.questions.quests.map((item: any, index: number) => {
			item.quest = JSON.parse(item.quest)
			return item;
		});
		// 因为有大小题，所以拉平该数组
		//const data = [{ father: 1, son: [1, 2], other: 'some value' }]; 转换为
		// [
		// { father: 1, son: [1], other: 'some value' },
		// { father: 1, son: [2], other: 'some value' }
		// ]
		state.question = state.question.reduce<any>((accu,item:any,index:number)=> {
			const sonLength = item.quest.subQuestion.length;
			for (let i = 0; i < sonLength; i++) {
				let newObj = JSON.parse(JSON.stringify({...item,subSeq: i+1,realSeqNum: index+1,isSingle: true}));
				console.log(item.quest.subQuestion[i],i,index);
				newObj.quest.subQuestion = [item.quest.subQuestion[i]]
				if(i >= 1 && newObj.isSingle){
					newObj.isSingle = false;
				}
				accu.push(newObj);
				newObj = {}
			}
			return accu;
		},[] as any)
		console.log(state.question)
	}


	//定时练习模式
	if(state.info.paper_type === 1){
		state.layout.left = 6;
		state.layout.middle = 18;
		state.layout.right = 0
		state.dialogVisible = true;
		const res = await api.getTimingPracticeStatus({
			group_id: state.coursewareId,
		})
		if(res.data?.code === 200 ) {
			state.timingStatus = res.data.data.status;
		}


	}else if (state.info.paper_type === 2){
		state.value = state.info.time_length * 1000;
	}
})

const submit = () => {
	// 有未做完的题目
	if(!isTipUndo()) {
		state.centerDialogVisible = true;
	} else {

		handleSubmit();
	}
}

// 因为大题标题被以卡片题目的形式给出了，所以需要过滤掉是标题的卡片题目，获取真索引
const getRealIndex = (index: number) => {
	let countTitle = 0;


	for (let i = 0; i < index; i++) {
		if(state.question[i].quest.asTitle === true){
			countTitle++;
		}
	}
	return index-countTitle;
}
// 因为大题标题被以卡片题目的形式给出了，所以需要过滤掉是标题的卡片题目，但是仍然要给这些卡片题目设置空答案，所以要反过来获取假顺序
const getFakeIndex = (quest: never) => {
	return state.question.indexOf(quest)
}


const handleExport = async () => {
	state.exportLoading = true;
	console.log(state.exportLoading);
	await htmlToPDF('middleCol', '导出内容');
	state.exportLoading = false;
	console.log(state.exportLoading);


}

// 把小题答案合并成大题答案
const unionSubToBig = () => {
	let questionLength =  state.question.length;
	// 给每个 未定义的userAnswerStore赋予初始值

	for (let i = 0; i < questionLength; i++) {
		if(!userAnswerStore.userAnswer[i]){
			userAnswerStore.userAnswer[i] = {
				template: "DaXiaoTi",
				time: 1000,
				userAnswer: getAllTypeStruct(state.question[i].quest.subQuestion[0].template)
			} as any
		}
	}
	debugger
	for (let i = 0; i < questionLength; i++) {
		if (state.question[i].subSeq !== 1) {
			if(!userAnswerStore.userAnswer[i]){
				console.log(getAllTypeStruct(state.question[i].quest.subQuestion[0].template),'空')
				userAnswerStore.userAnswer[i-(state.question[i].subSeq-1)].userAnswer.push((getAllTypeStruct(state.question[i].quest.subQuestion[0].template)?.userAnswer[0]) as any)
			} else{
				userAnswerStore.userAnswer[i-(state.question[i].subSeq-1)].userAnswer.push(userAnswerStore.userAnswer[i].userAnswer[0] as any)
			}
		}
	}
}
const handleSubmit = async () => {
	unionSubToBig();
	state.centerDialogVisible = false;
	let userAnswer = [];
	for (let i = 0; i < state.question.length; i++) {
		if(state.question[i].subSeq !== 1) {
			continue;
		}
		if(!userAnswerStore.userAnswer[i]){
			userAnswer.push({
				template: "DaXiaoTi",
				time: 1000,
				userAnswer: getAllTypeStruct(state.question[i].quest.subQuestion[0].template)
			})
		} else{
			userAnswer.push({
				template: "DaXiaoTi",
				time: 1000,
				userAnswer: userAnswerStore.userAnswer[i].userAnswer
			})
		}
	}

	const submitData = {
		group_id: String(state.coursewareId),
		class_id: String(state.classId),
		share_id: String(state.shareId),
		data: JSON.stringify(userAnswer),
		real_end: true,
		real_start: false,
		start_time: state.start_time,
		user_log: '[]',
	}
	const res = await api.submitUserAnswer(submitData);
	if(res && res.data.code === 200){
		ElMessage.success('提交成功');
	} else {
		ElMessage.error('提交失败');
	}

	state.drawer = true;
}

const scollIntoIndexQuest = (index: number):void => {
	const el = document.getElementById('quest-' + index);
	if (el) {
		el.scrollIntoView({behavior: "smooth",block: "center"});
	}
}

const isHaveAnswer1 = (index:number):boolean => {
	return userAnswerStore.userAnswer[index] !== undefined;
}

const isHaveAnswer = (index: number):boolean => {
	const type = state.question[index].quest.subQuestion[0].template;
	let result = false;
	switch (type) {
		case 'XuanZe':
		case 'PanDuan':
		case 'XieZi':
		case 'Card':
			result = isHaveAnswer1(index)
			break;
		case 'ZuoDa':
			result =  isHaveAnswer1(index) && Object.keys(userAnswerStore.userAnswer[index].userAnswer[0]).length  !== 0
			break;
		case 'TianKong':
			if(judgeTianKongAnswerType(index) ==='text'){
				result = isHaveAnswer1(index)  && userAnswerStore.userAnswer[index].userAnswer[0].text !== ''
			} else if(judgeTianKongAnswerType(index) ==='audio'){
				result = isHaveAnswer1(index)  && userAnswerStore.userAnswer[index].userAnswer[0].audios.length !== 0
			} else if (judgeTianKongAnswerType(index) ==='picture'){
				result = isHaveAnswer1(index)  && userAnswerStore.userAnswer[index].userAnswer[0].pics.length !== 0
			} else {
				result = isHaveAnswer1(index)  && userAnswerStore.userAnswer[index].userAnswer[0].writer[0].strokes.length  !== 0
			}
			break;
		case 'PaiXu':
		case 'LianXian':
			result = isHaveAnswer1(index) && userAnswerStore.userAnswer[index].userAnswer?.length != 0
			break;
		case 'DuiHua':
		case 'LangDu':
			result =  isHaveAnswer1(index) && userAnswerStore.userAnswer.audio !== ''
			break;
	}

	return result;
}

const judgeTianKongAnswerType = (index: number): string => {
	return state.question[index].quest.subQuestion[0].content.value[0][0];
}

const onConfirm = async () => {
	state.dialogVisible = false;
	// 调用开始作答接口

	startTimingPractice();
}

const pauseTimingPractice = async () => {
	const data = {
		group_id: state.coursewareId,
		share_id: state.shareId,
		answer: JSON.stringify(userAnswerStore.userAnswer)
	}
	const res = await api.pauseTimingPractice(data)
	console.log(res,'pause')
}
const startTimingPractice = async () => {
	state.dialogVisible = false;
	const data = {
		group_id: state.coursewareId,
		share_id: state.shareId
	}

	const res = await api.startTimingPractice(data)
	console.log(res,'start')
	if(res.data?.code === 200) {
		state.timingStatus = 1;
		state.value = res.data.data.time_length * 1000;
		start();
	}
}

const transformTime = (time_length:number) => {
	let data = {
		min: 0,
		sec: 0
	}
	data.min = time_length / 60;
	data.sec = time_length % 60;
	return data
}

const isTipUndo = () => {
	for (let i = 0; i < state.question.length; i++) {
		if(!isHaveAnswer(i)){
			state.centerDialogVisible = true;
			return false;
		}
	}
	return true
}


const getAllTypeStruct = (type: string) => {
	let userAnswer = null;
	switch (type) {
		case 'XuanZe':
			userAnswer = [{
				template: 'XuanZe',
				userAnswer: []
			}]
			break;
		case 'PanDuan':
			userAnswer = [{
				template: 'PanDuan',
				userAnswer: []
			}]
			break;
		case 'XieZi':
			userAnswer = [
				{
					template: "XieZi",
					score: 0,
					info: {
						allStrokeNum: 8,
						rewriteNum: 0,
						ziStrokeNum: 6,
						rightStrokeNum: 6
					},
					zi: '',
					strokes: []
				}
			]
			break;
		case 'Card':
			userAnswer = [{
				template: 'Card',
				userAnswer: []
			}]
			break;
		case 'ZuoDa':
			userAnswer = [{
				template: 'ZuoDa',
				userAnswer: []
			}]
			break;
		case 'TianKong':
			userAnswer = [{
				template: 'TianKong',
				userAnswer: [{
					text: '',
					pic: [],
					audio: [],
					writer: []
				}]

			}]
			break;
		case 'PaiXu':
			userAnswer = [{
				template: 'PaiXu',
				userAnswer: []
			}]
			break;

		case 'LianXian':
			userAnswer = [{
				template: 'LianXian',
				userAnswer: []
			}]
			break;
		case 'DuiHua':
			userAnswer = [{
				template: 'DuiHua',
			}]
			break;
		case 'LangDu':
			userAnswer = [{
				template: "LangDu",
				info: {
					playNum: 0,
					readNum: 1,
					recogRet: "识别服务未开启，未识别内容"
				},
				score: 0,
				audio: ''
			}]
			break;
	}

	return userAnswer

}
</script>

<style scoped lang="scss">
.coursewareContent {
	height: 95%;

	.stageQuizTitle {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 25px;
		font-weight: 700;
	}
	//background-color: pink;
	.el-row {
		height: 100%;
		display: flex;
		justify-content: space-around;
		.el-col {
			height: 100%;
			:deep(.el-divider--horizontal) {
				display: block;
				height: 1px;
				width: 120%;
				margin: 20px 0;
				border-top: 10px #f2f3f5 var(--el-border-style);
			}
			:deep(.el-divider--horizontal):nth-last-of-type(1) {
				height: 0;
				border-top: 0 #f2f3f5 var(--el-border-style);
			}
			.answerSheets {
				height: 95%;
				padding: 20px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: space-between;
				background-color: #fff;
				.top {
					.title {
						display: flex;
						justify-content: center;
						align-items: center;
						font-size: 20px;
						font-weight: bold;
					}

					.questionNumberBox {
						padding: 5px;
						display: flex;
						flex-wrap: wrap;
						cursor: pointer;

						.commonQuestionNum {
							width: 30px;
							height: 30px;
							margin: 5px;
							display: flex;
							align-items: center;
							justify-content: center;
						}
						.questionNumber {
							font-weight: 500;
							background-color: #f2f3f5;
						}
						.ActiveQuestionNum {
							color: #F2F3F5;
							background-color: #2260fc;
						}
					}
				}
				.timer {
					height: 95%;
					padding: 20px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					align-items: center;
					font-size: 30px;
					color: #303133;
					background-color: #fff;
					.top {
						display: flex;
						flex-direction: column;
						align-items: center;
					}
					.title {
						font-size: 18px;
						color: #616367;
					}
				}
				.bottom {
					height: 100px;
				}


			}

		}
		.middleCol {
			height: 100%;
			overflow-y: auto;
			overflow-x: hidden;
			background-color: #fff;
			.content {
				padding: 20px;
			}
		}
	}
	.drawer {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		height: 100%;
		span {
			font-size: 20px;
		}
		.el-image {
			margin-top: 20px;
		}
	}
}

</style>